package com.googlecode.garbagecan.springsecuritystudy.taglib;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;

public class SecurityTag extends TagSupport {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(SecurityTag.class);

	private String resourceName;
	public String getResourceName() {
		return resourceName;
	}
	public void setResourceName(String resourceName) {
		this.resourceName = resourceName;
	}

	public int doStartTag() throws JspException {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		GrantedAuthority[] grantedAuthorities = authentication.getAuthorities();
		for (GrantedAuthority grantedAuthority : grantedAuthorities) {
			logger.info(grantedAuthority.getAuthority());
		}
		
		// Query from RESC_ROLE table to get relation between resource and role
		String sql = "select role.name from RESC resc, RESC_ROLE rr, ROLE role "
				+ " where resc.name='"+resourceName+"'"
				+ " and resc.id=rr.resc_id "
				+ " and rr.role_id=role.id";
		List<String> roles = new ArrayList<String>();
		try {
			Class.forName("org.hsqldb.jdbcDriver");
			Connection conn = DriverManager.getConnection("jdbc:hsqldb:res:hsqldb/resmap", "sa", "");
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				roles.add(rs.getString(1));
			}
			ps.close();
			conn.commit();
			conn.close();
		} catch(Exception ex) {
			logger.error(ex.getMessage(), ex);
		}
		
		boolean bln = false;
		for (GrantedAuthority grantedAuthority : grantedAuthorities) {
			String authority = grantedAuthority.getAuthority();
			if (roles.contains(authority)) {
				bln = true;
			}
		}
		if (bln) {
			return (EVAL_BODY_INCLUDE);
		} else {
			return (SKIP_BODY);
		}
	}

	public int doEndTag() throws JspException {
		return (EVAL_PAGE);
	}

}
